/**
    Copyright (c) 2009~2011 ATTi 
    All rights reserved.
	Author: Michael Shu
	Date: 9/12/2011
*/

trigger caseUpdateContactAccount on Case (before insert, after insert, after update) {
	if(trigger.isBefore){
		if(trigger.isInsert){
			List<Case> NATOcases = new List<Case>();
			List<Case> IOGcases = new List<Case>();
			Set<ID> NATOCaseRTIds = GeneralConstants.getRecordTypeIdsByNames('Case', GeneralConstants.RT_NATL);
			Set<ID> IOGCaseRTIds = GeneralConstants.getRecordTypeIdsByNames('Case', GeneralConstants.RT_CCIR);
			for(Case c : Trigger.new){		
				if(NATOCaseRTIds.contains(c.RecordTypeId)){
					NATOcases.add(c);
				}else if(IOGCaseRTIds.contains(c.RecordTypeId)){
					IOGcases.add(c);
				}
			}
			caseUpdateContactAccountClass.limitAutoAssoiciationContactbyWebEmail(NATOcases, IOGcases);
			caseUpdateContactAccountClass.copyWebEmailToCaseContactEmailInitially(NATOcases);
		}
	}else if(trigger.isAfter){
		List<Case> followCases = new List<Case>();  	 
		List<Case> unfollowCases = new List<Case>();  	 
		if(trigger.isUpdate){  	
			List<Case> IOGcases = new List<Case>();
			Set<ID> IOGCaseRTIds = GeneralConstants.getRecordTypeIdsByNames('Case', GeneralConstants.RT_CCIR);		
	
			for(Case c : trigger.new){
				Case oldcs = trigger.oldMap.get(c.Id);	
				if(c.ContactId != null && c.AccountId != null && c.ContactId != oldcs.ContactId && IOGCaseRTIds.contains(c.RecordTypeId)){
					IOGcases.add(c);
				}
				if(!c.isClosed && c.AccountId != oldcs.AccountId && c.AccountId != null){
					followCases.add(c);
				}else if(c.isClosed && c.isClosed != oldcs.isClosed){
					unfollowCases.add(c);
				}
			}
			caseUpdateContactAccountClass.updateParentAccountOfContact(IOGcases);
		}
		if(trigger.isInsert){ 
			for(Case c : trigger.new){
				if(!c.isClosed && c.AccountId != null){
					followCases.add(c);
				}
			}
		}
		caseUpdateContactAccountClass.followAndunfollowCases(followCases, unfollowCases, trigger.isInsert);
	}
}